package com.emergency.db.service.impl.work;

import com.emergency.base.domain.Message;
import com.emergency.common.util.CommonUtils;
import com.emergency.common.util.IdWorker;
import com.emergency.db.dao.work.MessageDao;
import com.emergency.db.service.impl.staff.StaffServiceImpl;
import com.emergency.db.service.work.MessageService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class MessageServiceImpl implements MessageService {
    private final static Logger logger = LoggerFactory.getLogger(StaffServiceImpl.class);

    @Autowired
    private MessageDao messageDao;

    @Autowired
    private IdWorker idWorker;

    //保存
    public Long save(Message message) {
        if (CommonUtils.isNullOrEmpty(message.getId())) {
            message.setId(idWorker.nextId());
            message.setCreateTime(new Date());
        }
        messageDao.save(message);
        return message.getId();
    }

    //批量保存
    public void saveAll(List<Message> messageList) {
        messageList.forEach(message -> {
            if (CommonUtils.isNullOrEmpty(message.getId())) {
                message.setId(idWorker.nextId());
                message.setCreateTime(new Date());
            }
            messageDao.save(message);
        });
    }

    //查询单项
    public Message findById(Long id) {
        Message message = messageDao.findById(id).orElse(null);
        if (CommonUtils.isNullOrEmpty(message)) {
            logger.info("此信息为空！");
            return message;
        }
        return message;
    }

    //删除
    public Long delete(Long id) {
        messageDao.deleteById(id);
        return id;
    }

    //查询全部
    @Override
    public List<Message> findAll() {
        return messageDao.findAll();
    }

    //分页查询
    @Override
    public Page<Message> findList(Map searchMap, int page, int size) {
        Specification<Message> specification = createSpecification(searchMap);
        Sort sort = Sort.by(Sort.Direction.ASC, "id");
        PageRequest pageRequest = PageRequest.of(page - 1, size, sort);
        return messageDao.findAll(specification, pageRequest);
    }

    /**
     * 动态条件构建
     *
     * @param searchMap
     * @return
     */
    private Specification<Message> createSpecification(Map searchMap) {
        return new Specification<Message>() {

            @Override
            public Predicate toPredicate(Root<Message> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicateList = new ArrayList<Predicate>();

                // 文书主题
                if (searchMap.get("subject") != null && !"".equals(searchMap.get("subject"))) {
                    predicateList.add(criteriaBuilder.like(root.get("subject").as(String.class), "%" + (String) searchMap.get("subject") + "%"));
                }
                //发送方
                if (searchMap.get("sendUser") != null && !"".equals(searchMap.get("sendUser"))) {
                    predicateList.add(criteriaBuilder.like(root.get("sendUser").as(String.class), "%" + (String) searchMap.get("sendUser") + "%"));
                }
                //接收方
                if (searchMap.get("receiveUser") != null && !"".equals(searchMap.get("receiveUser"))) {
                    predicateList.add(criteriaBuilder.like(root.get("receiveUser").as(String.class), "%" + (String) searchMap.get("receiveUser") + "%"));
                }
                //文书状态
                if (searchMap.get("status") != null && !"".equals(searchMap.get("status"))) {
                    predicateList.add(criteriaBuilder.equal(root.get("status").as(Integer.class), (Integer) searchMap.get("status") + "%"));
                }
                //文书类型
                if (searchMap.get("type") != null && !"".equals(searchMap.get("type"))) {
                    predicateList.add(criteriaBuilder.like(root.get("type").as(String.class), "%" + (String) searchMap.get("type") + "%"));
                }
                return criteriaBuilder.and(predicateList.toArray(new Predicate[predicateList.size()]));
            }
        };
    }
}
